//
//  AppDelegate.m
//  JeemaaPersonal
//
//  Created by mac on 2017/9/28.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "AppDelegate.h"
#import "LoginViewController.h"
#import "OrderBaseControl.h"
#import "AppDelegate+configuration.h"
#import "AvoidCrash.h"
#import "IPhoneType.h"
//#import "UMessage.h"
#import "UploadViewController.h"
#import "TabbarController.h"
//#import <UserNotifications/UserNotifications.h>
#import <MMDrawerController/MMDrawerController.h>
#import "UIViewController+CurrentController.h"
#import "MJ_UserLoginViewModel.h"

// 引入JPush功能所需头文件
#import "JPUSHService.h"
// iOS10注册APNs所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif

@interface AppDelegate ()<UNUserNotificationCenterDelegate,UIDocumentInteractionControllerDelegate,JPUSHRegisterDelegate>

@end

@implementation AppDelegate

#pragma mark -- 文件分享
#pragma mark - UIDocumentInteractionControllerDelegate


- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL*)url
{
    return YES;
}

//ios9以下
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
    
    NSString *str = [[url absoluteString] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    if (str.length >0){
        shareData.filepath = str;
        shareData.weixinFileUrl = url;
        if ([userManager userIsOnline]) {
            MMDrawerController *menu = (MMDrawerController* )self.window.rootViewController;
            TabbarController *tbc = (TabbarController *)menu.centerViewController;
            if (tbc) {
                UINavigationController *nav = tbc.viewControllers[tbc.selectedIndex];
                UploadViewController *upVC = [[UploadViewController alloc] init];
                upVC.hidesBottomBarWhenPushed = YES;
                if (![nav.topViewController isMemberOfClass:[UploadViewController class]]) {
                    [nav pushViewController:upVC animated:YES];
                }
            }else {
                NSLog(@"%@",self.window.rootViewController);
            }
        }else{
            self.window.rootViewController = [LoginViewController new];
        }
        return YES;
    }else{
        return NO;
    }
}

//ios9以后
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options
{
    TGLog(@"从第三方软件中打开译马网");
    //传值
    NSString *str = [[url absoluteString] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    shareData.filepath = str;
    TGLog(@"filePath = %@, weixinFileUrl = %@",str,url);
    shareData.weixinFileUrl = url;
    if (str.length > 0) {
        if ([userManager userIsOnline]) {
            
            MMDrawerController *menu = (MMDrawerController *)self.window.rootViewController;
            TabbarController *tbc = (TabbarController *)menu.centerViewController;
            if (tbc) {
                UINavigationController *nav = tbc.viewControllers[tbc.selectedIndex];
                UploadViewController *upVC = [[UploadViewController alloc] init];
                upVC.hidesBottomBarWhenPushed = YES;
                if (![nav.topViewController isMemberOfClass:[UploadViewController class]]) {
                    [nav pushViewController:upVC animated:YES];
                }
            }
  
            
     
        }else{
            self.window.rootViewController = [LoginViewController new];
        }

    }
    return YES;
}


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    [NSThread sleepForTimeInterval:1.0];

    //设置初始根控制器
    [self configurationApplicationBaseContainer];
    
    [self setIQKeyboardTool];
    //监听网络状态
    [self startMonitoringNetworkReachabilityStatus];
    //崩溃
    [AvoidCrash becomeEffective];
    [JeemaaNotificationCenter  addObserver:self selector:@selector(dealwithCrashMessage:) name:AvoidCrashNotification object:nil];
    
//    //注册友盟推送
//    [UMessage startWithAppkey:@"58a520a1c62dca1fb3000aef" launchOptions:launchOptions httpsEnable:YES];
//    [UMessage registerForRemoteNotifications];
//    //iOS10必须加下面这段代码。
//    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
//    center.delegate = self;
//    UNAuthorizationOptions types10 = UNAuthorizationOptionBadge |  UNAuthorizationOptionAlert | UNAuthorizationOptionSound;
//    [center requestAuthorizationWithOptions:types10 completionHandler:^(BOOL granted, NSError * _Nullable error) {
//
//    }];
//    //打开日志，方便调试
//    [UMessage setLogEnabled:YES];
    
    //Required
    //notice: 3.0.0及以后版本注册可以这样写，也可以继续用之前的注册方式
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 可以添加自定义categories
        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    // Required
    // init Push
    // notice: 2.1.5版本的SDK新增的注册方法，改成可上报IDFA，如果没有使用IDFA直接传nil
    // 如需继续使用pushConfig.plist文件声明appKey等配置内容，请依旧使用[JPUSHService setupWithOption:launchOptions]方式初始化。
#ifdef DEBUG
    [JPUSHService setupWithOption:launchOptions appKey:@"bdadb704b4d89aa09eaf0b4d"
                          channel:@"App Store"
                 apsForProduction:0
            advertisingIdentifier:nil];
#else
    [JPUSHService setupWithOption:launchOptions appKey:@"bdadb704b4d89aa09eaf0b4d"
                          channel:@"App Store"
                 apsForProduction:1
            advertisingIdentifier:nil];
#endif
    return YES;
}


//获取device_Token
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
    
    NSString *deviceTokenString = [[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""]
                              stringByReplacingOccurrencesOfString: @">" withString: @""]
                             stringByReplacingOccurrencesOfString: @" " withString: @""];
    //保存deviceToken
    [userManager saveDeviceTokenWithString:deviceTokenString];
    TGLog(@"deviceToken = %@",deviceTokenString);
    [JPUSHService registerDeviceToken:deviceToken];
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
    TGLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    [JeemaaNotificationCenter postNotificationName:@"refreshOrderList" object:nil];
    [UserDefaults setBool:YES forKey:@"unreadMessage"];
    [[MJ_UserMessage sharedInstance] showBadgeWithMessageButton];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    // Required,For systems with less than or equal to iOS6
    [JPUSHService handleRemoteNotification:userInfo];
    [JeemaaNotificationCenter postNotificationName:@"refreshOrderList" object:nil];
    [UserDefaults setBool:YES forKey:@"unreadMessage"];
    [[MJ_UserMessage sharedInstance] showBadgeWithMessageButton];
}

//iOS10新增：处理前台收到通知的代理方法
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler
{

    [JeemaaNotificationCenter postNotificationName:@"refreshOrderList" object:nil];
    [UserDefaults setBool:YES forKey:@"unreadMessage"];
    [[MJ_UserMessage sharedInstance] showBadgeWithMessageButton];
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    [JPUSHService resetBadge];
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //应用处于前台时的远程推送接受
        [JPUSHService handleRemoteNotification:userInfo];
    }else{
        //应用处于前台时的本地推送接受
    }
    //当应用处于前台时提示设置，需要哪个可以设置哪一个
    completionHandler(UNNotificationPresentationOptionSound|UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionAlert);
}

- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {

    [JPUSHService resetBadge];
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //应用处于后台时的远程推送接受
        [JPUSHService handleRemoteNotification:userInfo];

    }else{
        //应用处于后台时的本地推送接受
    }
    completionHandler();  // 系统要求执行这个方法
}

//AvoidCrash崩溃信息
- (void)dealwithCrashMessage:(NSNotification *)note {
    TGLog(@"bugInfo == %@",note.userInfo);
}

- (void)applicationWillResignActive:(UIApplication *)application {
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    [JPUSHService resetBadge];
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    NSDate *lastDate = [UserDefaults objectForKey:@"timeRange"];
    if (lastDate == nil) {
        return;
    }
    NSDate *currentDate = [NSDate date];
    NSTimeInterval start = [lastDate timeIntervalSince1970]*1;
    NSTimeInterval end = [currentDate timeIntervalSince1970]*1;
    NSTimeInterval value = end - start;
    TGLog(@"time Range = %zd",(NSInteger)value);
    if ((NSInteger)value > 1800) {
        [LSProgressHUD showOnWindow];
        MJ_UserLoginViewModel *viewModel = [[MJ_UserLoginViewModel alloc] init];
        [viewModel autoLoginWithResult:^(BOOL success) {
            if (!success) {
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"登录超时，请重新登录" preferredStyle:UIAlertControllerStyleAlert];
        
                UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [[MJ_UserMessage sharedInstance] userLogOut];
                    [UIApplication sharedApplication].keyWindow.rootViewController = [LoginViewController new];
                }];
                [alert addAction:action];
                [[UIViewController currentViewController] presentViewController:alert animated:YES completion:nil];
            }
            [LSProgressHUD hideForWindow];
        }];

    }
}
- (void)applicationWillTerminate:(UIApplication *)application {
}



@end

